package main

import (
	"crypto/tls"
	"fmt"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/acme/autocert"
	"https_golang/router"
	"net/http"
	"os"
	"path/filepath"
)

func main() {
	var engin = gin.Default()
	router.InitRouter(engin)

	var server = tool(engin)
	err := server.ListenAndServeTLS("", "")
	if err != nil {
		fmt.Println(err)
		return
	}

	//engin.Run(":7000")
}

func tool(r *gin.Engine) *http.Server {
	var currentWorkingDir, _ = os.Getwd()
	var path = filepath.Join(currentWorkingDir, "certificate")

	// 自动证书管理器
	m := autocert.Manager{
		Prompt:     autocert.AcceptTOS,
		Cache:      autocert.DirCache(path), // 缓存证书的文件夹
		HostPolicy: autocert.HostWhitelist("oceansimple.online"),
	}

	// 配置 TLS
	server := &http.Server{
		Addr:    ":443",
		Handler: r,
		TLSConfig: &tls.Config{
			GetCertificate: m.GetCertificate, // 自动获取证书
		},
	}

	// HTTP 服务器（80 端口，处理 HTTP-01 验证和重定向）
	httpServer := &http.Server{
		Addr: ":80",
		Handler: m.HTTPHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// 可选：将 HTTP 请求重定向到 HTTPS
			http.Redirect(w, r, "https://"+r.Host+r.URL.String(), http.StatusMovedPermanently)
		})),
	}
	go httpServer.ListenAndServe()

	return server
}
